﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using NF.Core;
using NF.Core.SOM;
using System.Windows.Threading;
using System.IO;

namespace NF.Clustering
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            mSom = new SelfOrganizingMap();

            String dir = Directory.GetCurrentDirectory();
            var data = ReadData("Dada.txt");

            mSom.Build(4, 4, data);
            mSomPreview.ChannelIndices[0] = 0;
            mSomPreview.ChannelIndices[1] = 1;
            mSomPreview.ChannelIndices[2] = 2;

            mMaxIterations = 1000;
            mIteration = 0;

            mTimer = new DispatcherTimer();
            mTimer.Interval = new TimeSpan(0, 0, 0, 0, 500);
            mTimer.Tick += new EventHandler(timer_Tick);

            mTimer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            mSom.Iteration((double)mIteration / (double)mMaxIterations);
            mSomPreview.Update(mSom);
            if (mIteration.Equals(mMaxIterations))
            {
                DispatcherTimer dt = (DispatcherTimer)sender;
                dt.Stop();
            }
            else
                mIteration++;
        }

        private static IEnumerable<NPoint> ReadData(String filename)
        {
            using (var r = File.OpenText(filename))
            {
                List<NPoint> data = new List<NPoint>();
                String l;
                String[] s;

                while ((l = r.ReadLine()) != null)
                {
                    s = l.Split(',');
                    NPoint pt = new NPoint(s.Length - 1);

                    for (int i = 0; i < s.Length - 1; ++i)
                        pt[i] = double.Parse(s[i], System.Globalization.CultureInfo.InvariantCulture.NumberFormat);

                    data.Add(pt);
                }

                return data;
            }
        }

        private DispatcherTimer mTimer;
        private int mIteration;
        private int mMaxIterations;
        private SelfOrganizingMap mSom;
    }
}
